<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Axios 二次封装</title>
  <link crossorigin="anonymous" href="https://cdn.bootcss.com/nprogress/0.2.0/nprogress.css" rel="stylesheet">
  <script crossorigin="anonymous" src="https://cdn.bootcss.com/nprogress/0.2.0/nprogress.js"></script>
  <script crossorigin="anonymous" src="https://cdn.bootcss.com/axios/0.19.2/axios.min.js"></script>
</head>

<body>
  <!-- 
    测试接口1: https://api.github.com/search/repositories?q=v&sort=stars
    测试接口1: https://api.github.com/search/users?q=v
  -->
  <!--
   1). 统一进行请求配置: 基础路径/超时时间等
   2). 请求过程中loading提示
   3). 请求可能需要携带token数据
   4). 请求成功的value不再是response, 而是response.data
   5). 请求失败/出错统一进行处理, 每个请求可以不用单独处理
  -->
  <div>
    <button onclick="getUsers()">获取用户列表</button>
    <button onclick="getRepos()">获取仓库列表</button>
  </div>

  <script>
    //axios 基础配置
    axios.defaults.baseURL = 'https://api.github.com';
    axios.defaults.timeout = 3000;

    //设置请求拦截器
    axios.interceptors.request.use(config => {
      //开始loading
      NProgress.start();
      //为每一个请求添加公共的参数
      config.params = {test:100};
      return config;
    }, error => {
      return Promise.reject(error);
    });
    //设置响应拦截器
    axios.interceptors.response.use(response => {
      //停止进度条
      NProgress.done();
      return response.data;
    }, error => {
      //这里对失败的结果进行统一处理
      console.error(error);
      return new Promise(() => {});
    });

    function getUsers(){
      axios({
        url: '/search/users?q=v',
        method:'GET'
      }).then(response => {
        console.log(response);
      });

    }

    function getRepos(){
      axios({
        url: '/search/repositories?q=v&sort=stars',
        method:'GET'
      }).then(response => {
        console.log(response);
      });
    }

  </script>


</body>

</html>